let express = require('express')
let router = express.Router()

let mysqlHelper = require('../utils/mysqlHelper.js')
const utils = require('../utils/utils.js')


// 查询 maoyuan  keyword检索
router.get('/list', async function (req, res, next) {
    let result = {}
    try {
        let page = utils.getQueryValue(req.query.page)
        let pageSize = utils.getQueryValue(req.query.pageSize)
        let sqlLimit = " limit " + (page - 1) * pageSize + ", " + pageSize
        sqlLimit = ((sqlLimit.indexOf('NaN')>-1 || sqlLimit.indexOf("undefined")>-1 || pageSize=='' || page=='') ? "" : sqlLimit)
        let keyword = utils.getQueryValue(req.query.keyword)
        let level = utils.getQueryValue(req.query.level)

        let startTime = utils.getQueryValue(req.query.startTime)
        let endTime = utils.getQueryValue(req.query.endTime)

        let sqlWhere = " WHERE 1=1"
        sqlWhere += (keyword != '' ? " and (name like '%" + keyword + "%' or userName like '%" + keyword + "%') " : "")
        sqlWhere += (level != '' ? " and level='"+level+"'" : "")
        sqlWhere += (startTime != '' ? " and time>='"+startTime+"'" : "")
        sqlWhere += (endTime != '' ? " and time<='"+endTime+"'" : "")

        total = (await mysqlHelper.query("select count(1) as ct from sys_log u " + sqlWhere))[0].ct
        let prop = utils.getQueryValue(req.query.prop)
        let order = utils.getQueryValue(req.query.order)
        if (order=='ascending')
            order="ASC"
        else if (order=='descending')
            order='DESC'
        let sqlOrder = " ORDER by " + prop+" "+ order
        sqlOrder = ((prop.indexOf('NaN')>-1 || order.indexOf("undefined")>-1 || prop=='' || order=='') ? "" : sqlOrder)

        let sqlStr = "select * from (    \
                        select l.*,d.label as levellabel from sys_log l left join sys_dict_detail d on l.level=d.value  \
                        where d.dict_id=(select id from sys_dict where code='syslog')       \
                      ) raw "
        sqlStr += sqlWhere + sqlOrder + sqlLimit 
        rows = await mysqlHelper.query(sqlStr)
        rows.forEach((user, index, arr) => {
            user.group = (user.group ? user.group.split(',') : [])
        })
        result.code = 200
        result.data = {
            'total': total,
            'page': page,
            'pageSize': pageSize,
            'summary': {
                'id': page * pageSize,
                'name': '999'
            },
            rows: rows
        }
        result.message = ''
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

module.exports = router

